package com.ifcar.app.adapter;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.CommonFrameActivity;
import com.ifcar.app.activity.LinkOutSide;
import com.ifcar.app.activity.ShowBigPic;
import com.ifcar.app.activity.common.CommentFragment;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.GroupAdapter;
import com.ifcar.app.util.MicroHotShare;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.MicroHotToolsPopupWindow;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;


public class MicroHotAdapter extends GroupAdapter<Map<String, Object>, Map<String, Object>> implements OnTouchListener{
	
	private Context mContext;
	private LayoutInflater mInflater;
	private ThemeSettingsHelper mThemeSettingsHelper;

	private MicroHotToolsPopupWindow mMicroHotPopupWindow;
	private MicroHotToolsPopupWindow mMicroHotPopupWindowNoOriginal;
	private int mToolPopupX;
    private int mToolPopupY;
    
    private boolean mIsDownloadPic = false;

    public final static String REPLAY_STRING_TAG= "的回复";
    private final String IS_REPLAY_TAG = "is_wb_replay";
    
	public MicroHotAdapter(Context context,
			List<Pair<Map<String, Object>, List<Map<String, Object>>>> list) {
		super(list);
		// TODO Auto-generated constructor stub
		mContext = context;
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
		mIsDownloadPic = sp.getBoolean("downpic", false);
		
		mInflater = LayoutInflater.from(mContext);
		mThemeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(mContext);
		
		mMicroHotPopupWindow = new MicroHotToolsPopupWindow(mContext);
		mMicroHotPopupWindow.setContentView(R.layout.microhot_popupwindow_tools);
		mMicroHotPopupWindow.setOnClickListener(mViewClickListener, new int[] {
                R.id.send, R.id.go_original});
		
		mMicroHotPopupWindowNoOriginal = new MicroHotToolsPopupWindow(mContext);
		mMicroHotPopupWindowNoOriginal.setContentView(R.layout.microhot_popupwindow_tools_original);
		mMicroHotPopupWindowNoOriginal.setOnClickListener(mViewClickListener, new int[] {
                R.id.send_original});
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		
		if(null == convertView){
			ChildViewHolder holder = new ChildViewHolder();
			convertView = mInflater.inflate(R.layout.microhot_child_layout, null);
			holder.mWbTextLayout = convertView.findViewById(R.id.wb_text_layout);
			holder.mChildSplitView = convertView.findViewById(R.id.child_split_view);
			holder.mWbAuthor = (TextView) convertView.findViewById(R.id.wb_author);
			holder.mWbFlag = (TextView) convertView.findViewById(R.id.wb_flag);
			holder.mWbText = (TextView) convertView.findViewById(R.id.wb_text);
			convertView.setTag(holder);
		}
		
		ChildViewHolder holder = (ChildViewHolder) convertView.getTag();
		
		int childcount = getChildrenCount(groupPosition);
		if(childPosition < (childcount - 1)){
			mThemeSettingsHelper.setViewBackgroud(mContext, holder.mWbTextLayout, R.drawable.microhot_middle_bg);
			holder.mWbTextLayout.setPadding(10, 10, 10, 15);
		} else {
			mThemeSettingsHelper.setViewBackgroud(mContext, holder.mWbTextLayout, R.drawable.microhot_bottom_bg);
			holder.mWbTextLayout.setPadding(10, 10, 10, 25);
		}
		
		Map<String, Object> map = getChild(groupPosition, childPosition);
		String text = (String) map.get(GetColumnsInfo.TEXT_TAG);
		
		boolean isReplay = false;
		String author = StringUtil.findMicrohotAthor(text, false);
		SpannableString sp = new SpannableString(author);
		int authorColor = mThemeSettingsHelper.getThemeColor(mContext, R.color.microhot_author_text_color).getDefaultColor();
		sp.setSpan(new ForegroundColorSpan(authorColor), 0, author.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		
		if(author.contains(REPLAY_STRING_TAG)){
			sp.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.microhot_wbtext)), author.length() - 3, author.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			isReplay = true;
		}
		map.put(IS_REPLAY_TAG, isReplay);
		
		holder.mWbAuthor.setText(sp);
		try {
	           text = text.substring(text.indexOf(author) + author.length() + 1, text.length());
	           holder.mWbText.setText(Tools.FilterCNSpace(text));
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            holder.mWbText.setText(text);
	            e.printStackTrace();
	        }
		
		String url = (String) map.get(GetColumnsInfo.URL_TAG);
		setWbFlag(url, holder.mWbFlag);
		
		List<Map<String, Object>> images = (List<Map<String, Object>>) map.get(GetColumnsInfo.IMAGES_TAG);
		
		if(null != images && images.size() > 0){ // 处理图片
			String imgUrl = (String) images.get(0).get(GetColumnsInfo.SRC_TAG);
			if(!TextUtils.isEmpty(imgUrl)){
                Map imgMap = new HashMap();
                ImageView imageView = (ImageView) holder.mWbTextLayout.findViewById(R.id.wb_image);
                holder.mWbTextLayout.findViewById(R.id.image_frame_layout).setVisibility(View.VISIBLE);
                downloadWbImage(imgUrl, imageView);
                imageView.setOnClickListener(mViewClickListener);
                imgMap.put("imgurl", imgUrl);
                imgMap.put("alt", ""+images.get(0).get(GetColumnsInfo.ALT_TAG));
                imageView.setTag(imgMap);
                mThemeSettingsHelper.setImageViewSrc(mContext, (ImageView)holder.mWbTextLayout.findViewById(R.id.scale_add_flag), R.drawable.add);
            }
		}else{
			holder.mWbTextLayout.findViewById(R.id.image_frame_layout).setVisibility(View.GONE);
		}
		
		holder.mWbTextLayout.setOnClickListener(mViewClickListener);
		holder.mWbTextLayout.setOnTouchListener(this);
		holder.mWbText.setTag(map); 
		
		// 夜间模式
		mThemeSettingsHelper.setViewBackgroud(mContext, holder.mChildSplitView, R.drawable.list_divider_line);
		mThemeSettingsHelper.setTextViewColor(mContext, holder.mWbText, R.color.microhot_wbtext);
		holder.mChildSplitView.setPadding(1, 0, 1, 0);
		
		return convertView;
	}
	
	/**
	 * 下载微热点中的微博图片
	 * @param url
	 * @param imageView
	 */
	private void downloadWbImage(String url, ImageView imageView) {
		// TODO Auto-generated method stub
		
		Pair<String, ImageView> p = Pair.create(url, imageView);
		
		final String imageName = url.substring(url.lastIndexOf("/")+1, url.length());
		
		String smallName = imageName.replace(".", "_small.");
		if(PicUtil.isLocalPicExit(smallName)){
			WeakReference<Bitmap> wbm = new WeakReference<Bitmap>(PicUtil.readTempJPEGFile(smallName));
			if(null != wbm.get()){
				imageView.setImageBitmap(wbm.get());
				return;
			}
		}
		imageView.setImageResource(R.drawable.default_microhot);
		
		if(Tools.isshowimg(mIsDownloadPic, mContext)){
			
			new AsyncTask<Object, Void, Object>(){
				
				protected Object doInBackground(Object... params) {
					if(null == params) return null;
					
					Pair<WeakReference<Bitmap>, ImageView> result = null;
					
					Pair<String, ImageView> pair = (Pair<String, ImageView>) params[0];
					String url = pair.first;
					
					Bitmap bitmap = PicUtil.getBitMapForStringURL(url, mContext);
					if(null != bitmap){
						PicUtil.saveMyBitmap(imageName, bitmap);
						
						int w = bitmap.getWidth();
						int h = bitmap.getHeight();
						
						int rw = (int)mContext.getResources().getDimension(R.dimen.wb_image_width);
						int rh = (int)mContext.getResources().getDimension(R.dimen.wb_image_hight);
						
						int picSize = (int)mContext.getResources().getDimension(R.dimen.wb_image_size);
						
						if(Math.min(w, h) > picSize) {
							if(w>h) {
								w = (int) (picSize * ((float)w/(float)h));
								h = picSize;
							} else {
								h = (int) (picSize * ((float)h/(float)w));
								w = picSize; 
							}
						}
						
						WeakReference<Bitmap> smallBitmap = new WeakReference<Bitmap>(PicUtil.cutBitmap4DetailPage(PicUtil.resizeBitmap(mContext, bitmap, w, h), rw, rh));
						PicUtil.saveMyBitmap(imageName.replace(".", "_small."), smallBitmap.get());
						result = Pair.create(smallBitmap, pair.second);
						
						if(null != bitmap){
							bitmap.recycle(); bitmap = null;
						}
						
					}
					
					return result;
				};
				
				protected void onPostExecute(final Object result) {
					if(null == result) return;
					//TODO 可能有异常，暂时用这种方法解决
					mHandler.post(new Runnable() {
                        
                        @Override
                        public void run() {
                            Pair<WeakReference<Bitmap>, ImageView> pair = (Pair<WeakReference<Bitmap>, ImageView>) result;
                            pair.second.setImageBitmap(pair.first.get()); 
                        }
                    });

				};
				
			}.execute(p); 
		}
	}
	private Handler mHandler = new Handler();
	
	private View.OnClickListener mViewClickListener = new View.OnClickListener(){
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.wb_text_layout:
				Map<String, Object> map = (Map<String, Object>) v.findViewById(R.id.wb_text).getTag();
				setMicroHotPopupWindow(map, v);
				break;
			case R.id.wb_image:
                Intent intent = new Intent(mContext, ShowBigPic.class);
                Bundle b = new Bundle();
                Map imgMap = (Map) v.getTag();
                String url = "";
                String alt = "";
                if(null!=imgMap){
                    url = (String)imgMap.get("imgurl");
                    alt = (String)imgMap.get("alt");
                    url = null==url?"":url;
                    alt = null==alt?"":alt;
                }
                b.putString(GetColumnsInfo.DOWNLOAD_IMGSRC_TAG, url.replace(".", "_small."));
                b.putString(GetColumnsInfo.ALT_TAG,alt);
                intent.putExtras(b);
                mContext.startActivity(intent);
                resetWindow();
				break;
			case R.id.microhot_comment_num:
				goCommentPage(v);
				resetWindow();
				break;
				
			case R.id.send: // 微热点转发
				map = (Map<String, Object>) mMicroHotPopupWindow.getTag();
				sendMicroBlog(map);
				resetWindow();
				break;
			case R.id.send_original:
				map = (Map<String, Object>) mMicroHotPopupWindowNoOriginal.getTag();
				sendMicroBlog(map);
				resetWindow();
				break;
			case R.id.go_original: // 微热点原微博
				map = (Map<String, Object>) mMicroHotPopupWindow.getTag();
				
				url = (String) map.get(GetColumnsInfo.M_URL_TAG);
				
				if(TextUtils.isEmpty(url)){
					url = (String) map.get(GetColumnsInfo.URL_TAG);
				}
				if(TextUtils.isEmpty(url)){
					Toast.makeText(mContext, R.string.microhot_url_isnull, Toast.LENGTH_SHORT).show();
					mMicroHotPopupWindow.dismiss();
					return;
				}
				Intent i = new Intent(mContext,LinkOutSide.class);
	            Bundle extras = new Bundle();
	            extras.putString("href", url);
	            i.putExtras(extras);
	            mContext.startActivity(i);
	            resetWindow();
				break;
			}
			
		}
	};
	
	private void resetWindow(){
		mMicroHotPopupWindow.dismiss();
		mMicroHotPopupWindowNoOriginal.dismiss();
	}
	
	/**
	 * 工具条
	 * @param map
	 */
	protected void setMicroHotPopupWindow(Map<String, Object> map, View v) {
		// TODO Auto-generated method stub
		boolean isReplay = (Boolean) map.get(IS_REPLAY_TAG);
		
		if(isReplay){
			showToolBars(mMicroHotPopupWindowNoOriginal, map, v);
		}else{
			showToolBars(mMicroHotPopupWindow, map, v);
		}
	}
	
	private void showToolBars(MicroHotToolsPopupWindow window, Map<String, Object> map, View v){
		window.setTag(map);
		int height = (int)(mContext.getResources().getDisplayMetrics().density * 55);
		window.showAsDropDown(v, mToolPopupX, mToolPopupY - v.getHeight() - height);
		
	}
	
	/**
	 * 转发微博
	 * @param map
	 */
	protected void sendMicroBlog(Map<String, Object> map) {
		// TODO Auto-generated method stub
		if (map != null) {
			MicroHotShare.showShareDialog(mContext, StringUtil.GetString(map.get(GetColumnsInfo.TEXT_TAG)), map);
        }
	}

	protected void goCommentPage(View v) {
		// TODO Auto-generated method stub
		Map<String, Object> map = (Map<String, Object>) v.getTag();
		
		String boardId = (String)map.get(GetColumnsInfo.REPLYBOARD_TAG);
		String postId = (String)map.get(GetColumnsInfo.REPLYID_TAG);
		Object replyCount = map.get(GetColumnsInfo.REPLYCOUNT_TAG);
		String tieTitle = (String)map.get(GetColumnsInfo.TITLE_TAG);
		boolean hasComment = false;
		if(null != replyCount){
			int number = (Integer) replyCount;
			if(number > 0){
				hasComment = true;
			}
			
		} else {
			hasComment = false;
		}
		
//		if(!hasComment){
//			Toast.makeText(mContext, mContext.getString(R.string.msg_no_comment), Toast.LENGTH_SHORT).show();
//			return;
//		}
		
//		Intent intent = new Intent(mContext, ShowComments.class);
//		Bundle b = new Bundle();
//		
//		b.putInt(StringUtil.COMMENT_COLUMN_ID, 1);
//		
//		b.putString(GetColumnsInfo.REPLYBOARD_TAG, boardId);
//		b.putString(GetColumnsInfo.TITLE_TAG, tieTitle);
//		b.putString(GetColumnsInfo.POSTID_TAG, postId);
//		b.putString(GetColumnsInfo.REPLYCOUNT_TAG, String.valueOf(replyCount));
//		b.putBoolean("frommicrohot", true);
//		intent.putExtras(b);
		
		Bundle bundle = new Bundle();
        bundle.putString(CommentFragment.BOARD_ID, boardId);
        bundle.putString(CommentFragment.DOC_ID, postId);
        bundle.putString(CommentFragment.DOC_TITLE, tieTitle);
		Intent intent = CommonFrameActivity.getStartIntent(mContext, CommentFragment.class, "mirco_hot_comment", bundle);
		
		mContext.startActivity(intent);
		
	}
	
	private void setWbFlag(String url, TextView textView) {
		// TODO Auto-generated method stub
		if(!TextUtils.isEmpty(url)){
			textView.setVisibility(View.VISIBLE);
			if(url.contains("weibo.com") || url.contains("t.sina")){
				setImage(textView, R.drawable.sina_flag, null);
			}else if(url.contains("t.qq.com")){
				setImage(textView, R.drawable.qq_flag, null);
			}else if(url.contains("t.163.com")){
				setImage(textView, R.drawable.netease_flag, null);
			}else if(url.contains("t.sohu.com")){
				setImage(textView, -1, "搜狐微博");
			}else if(url.contains("t.people.com.cn")){
				setImage(textView, -1, "人民微博");
			}else if(url.contains("t.cankaoxiaoxi.com")){
				setImage(textView, -1, "参考消息微博");
			}else if(url.contains("t.hexun.com")){
				setImage(textView, -1, "和讯微博");
			}else if(url.contains("my.tianya.cn")){
				setImage(textView, -1, "天涯微博");
			}else if(url.contains("t.ifeng.com")){
				setImage(textView, -1, "凤凰网微博");
			}else if(url.contains("t.home.news.cn")){
				setImage(textView, -1, "新华微博");
			}else if(url.contains("t.cntv.cn")){
				setImage(textView, -1, "CNTV微博");
			} else {
				setImage(textView, -1, "其他");
			}
		} else {
			textView.setVisibility(View.INVISIBLE);
		}
	}
	
	private void setImage(TextView textView, int imgId, String text){
		if(null == text && -1 != imgId){
			Drawable drawable = mContext.getResources().getDrawable(imgId);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
			SpannableString spannableString = new SpannableString("pic");  
			ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE);  
			spannableString.setSpan(imageSpan, 0, spannableString.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
			textView.setText(spannableString);
		} else {
			textView.setText(text);
		}
	}

	@Override
	public View getGroupView(int groupPosition, View convertView,
			ViewGroup parent) {
		// TODO Auto-generated method stub
		if(null == convertView){
			GroupViewHolder holder = new GroupViewHolder();
			convertView = mInflater.inflate(R.layout.microhot_group_layout, null);
			holder.mRightSpace = (ImageView)convertView.findViewById(R.id.group_space_right);
			holder.mGroupTextLayout = convertView.findViewById(R.id.group_text_layout);
			holder.mWbDiscribe = (TextView) convertView.findViewById(R.id.wb_digest);
			holder.mTitle = (TextView) convertView.findViewById(R.id.category_title);
			holder.mPtime = (TextView) convertView.findViewById(R.id.microhot_ptime);
			holder.mCommentNum = (Button) convertView.findViewById(R.id.microhot_comment_num);
			convertView.setTag(holder);
		}
		
		final GroupViewHolder holder = (GroupViewHolder) convertView.getTag();
		Map<String, Object> map = getGroup(groupPosition);
		String title = (String) map.get(GetColumnsInfo.TITLE_TAG);
		Integer commentNum = (Integer) map.get(GetColumnsInfo.REPLYCOUNT_TAG);
		String digest = (String) map.get(GetColumnsInfo.DIGEST_TAG);
		try {
			holder.mWbDiscribe.setText(Tools.FilterCNSpace(StringUtil.delSpaceStr(digest)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			holder.mWbDiscribe.setText(StringUtil.delSpaceStr(digest));
		}
		
		String ptime = (String) map.get(GetColumnsInfo.PTIME_TAG);
		holder.mPtime.setText(StringUtil.getDate(ptime));
		
		holder.mTitle.setText(title);
		holder.mCommentNum.setText(mContext.getString(R.string.commnet_num_string, commentNum));
		holder.mCommentNum.setOnClickListener(mViewClickListener);
		holder.mCommentNum.setTag(map);
		
		// 夜间模式
		mThemeSettingsHelper.setImageViewSrc(mContext, holder.mRightSpace, R.drawable.microhot_space_right);
		mThemeSettingsHelper.setViewBackgroud(mContext, holder.mGroupTextLayout, R.drawable.microhot_group_bg);
		holder.mGroupTextLayout.setPadding(10, 10, 10, 10);
		mThemeSettingsHelper.setTextViewColor(mContext, holder.mPtime, R.color.microhot_ptime);
		mThemeSettingsHelper.setTextViewColor(mContext, holder.mWbDiscribe, R.color.microhot_discribe);
		mThemeSettingsHelper.setTextViewColor(mContext, holder.mCommentNum, R.color.top_image_title_color);
		
		mThemeSettingsHelper.setViewBackgroud(mContext, holder.mCommentNum, R.drawable.microhot_comment_btn);
		holder.mCommentNum.setPadding(10, 5, 10, 10);
		
		return convertView;
	}
	
	class GroupViewHolder{
		ImageView mRightSpace;
		TextView mWbDiscribe;
		View mGroupTextLayout;
		TextView mTitle;
		TextView mPtime;
		Button mCommentNum;
	}
	
	class ChildViewHolder{
		View mWbTextLayout;
		View mChildSplitView;
		TextView mWbAuthor;
		TextView mWbFlag;
		TextView mWbText;
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_UP) {
		    if (mMicroHotPopupWindow != null && mMicroHotPopupWindow.isHide()) {
		        mMicroHotPopupWindow.dismiss();
                return true;
            }
		    
		    if (mMicroHotPopupWindowNoOriginal != null && mMicroHotPopupWindowNoOriginal.isHide()) {
		        mMicroHotPopupWindowNoOriginal.dismiss();
                return true;
            }
		    
            mToolPopupX = (int)event.getX();
            mToolPopupY = (int)event.getY();
        }
		return false;
	}
	
}
